<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="stylesheet" href="style.css" />
  <title>My Blog</title>
</head>

<body>

  <div id="posts-container">
    <div class="post">
      <div class="number">1</div>
      <div class="post-info">
        <h2 class="post-title">sunt aut facere repellat provident occaecati excepturi optio reprehenderit</h2>
        <p class="post-body">quia et suscipit
          suscipit recusandae consequuntur expedita et cum
          reprehenderit molestiae ut ut quas totam
          nostrum rerum est autem sunt rem eveniet architecto</p>
      </div>
    </div>
  </div>

  <div class="loader">
    <div class="circle"></div>
    <div class="circle"></div>
    <div class="circle"></div>
  </div>
  <script src="./axios.js"></script>
  <script>
    //封装函数getCommentList()获取端口数据内容并渲染
    //上拉显示更多内容并渲染
    let page = 1 //初始页码
    let isLoading = false //是否正在加载中
    const postBox = document.querySelector('#posts-container')//数据框盒子
    const loaderbox = document.querySelector('.loader')//加载中图标盒子
    
    async function getCommentList(page=1) {
      let res = await axios({
        url: 'https://jsonplaceholder.typicode.com/posts',
        method: 'GET',
        params: {
          _limit: 5, //每页显示数量
          _page: page
        }
      })
      console.log(res.data);
      return res.data//返回数据
    }

    //封装函数xuanran()并渲染字符串
    async function xuanran() {
      let str = ''
      let textBox = await getCommentList(page)
      textBox.forEach(item => {
        str += `
        <div class="post">
      <div class="number">${item.id}</div>
      <div class="post-info">
        <h2 class="post-title">${item.title}</h2>
        <p class="post-body">${item.body}</p>
      </div>
    </div>
        `

      })
      postBox.innerHTML = str//渲染字符串
    }

    //滚动到滚动条距离页面底部 50px 时，加载下一页数据
    window.addEventListener('scroll', async function () {
      const { scrollTop, scrollHeight, clientHeight } = document.documentElement//获取滚动条距离页面顶部高度，页面总高度，可视区域高度

      if (clientHeight + scrollTop >= scrollHeight - 50 && !isLoading) { //clientHeight:可视区域高度，scrollTo:滚动条距离页面顶部高度，scrollHeight:页面总高度
        isLoading = true//防止重复加载
        loaderbox.classList.add('show') //加载动画显示
        page++ //页码下一页
        await xuanran()//渲染下一页数据
        isLoading = false//加载完成
        loaderbox.classList.remove('show') //加载动画隐藏
      }
    })



    //调用函数
    xuanran()
  </script>
</body>

</html>